library flutter_common;

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_common/ui/flutter_error.dart';
import 'package:flutter/foundation.dart';
import 'dart:io' as p show Platform;

import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 主题参数设置
class FxTheme {

  static FxTheme get instance => _instance;
  static final FxTheme _instance = FxTheme._();
  factory FxTheme() => _instance;

  FxTheme._();

  Color textColor = Colors.black45;
  Color backgroundColor = const Color(0xff2A81FF);
  Color buttonColor = const Color(0xff2A81FF);
  Color buttonDisableColor = const Color(0xFFD9D9D9);
  Color appBarBgColor = Colors.white;

  ///横向的分割线
  get line => Line();

  Line({double left = 0, double right = 0, double height = 0.51}) =>
      Container(height: height,
          color: Colors.grey[300],
          margin: EdgeInsets.only(left: left, right: right));
  
  ///竖向的分割线
  get vLine => Container(width: 0.51, color: Colors.grey[300]);

  get dialogType => DialogNavigatorObserver._dialogType;
  get isDialogShow => dialogType != null;

  ///状态栏是黑色主题，导航栏是白色主题
  SystemUiOverlayStyle get darkUiStyleWhiteNavigationBar =>
      const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        systemNavigationBarColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.dark,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      );
}

abstract class FxMaterialApp extends StatefulWidget {

  const FxMaterialApp({super.key});

  @override
  State<StatefulWidget> createState() => _FxMaterialState();

  Widget buildMaterialApp(GlobalKey<NavigatorState> navigatorKey);
  void handlerExceptionMessage(String msg);
  void initState() {}
  void didChangeAppLifecycleState(AppLifecycleState state) {}
  Size designSize() => const Size(750, 1330);
  bool showErrorDialog() => true;

  mountedState([VoidCallback? fn]) {
    if(_FxMaterialState._state?.mounted == true) {
      _FxMaterialState._state!.setState(fn??(){});
    }
  }
}

class _FxMaterialState extends State<FxMaterialApp> with WidgetsBindingObserver {

  GlobalKey<NavigatorState> navigatorKey = GlobalKey();
  static _FxMaterialState? _state;

  @override
  void initState() {
    super.initState();
    _state = this;
    WidgetsBinding.instance.addObserver(this);
    initErrorReport(navigatorKey, (p0) => widget.handlerExceptionMessage(p0),
        widget.showErrorDialog());
    widget.initState();
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    _state = null;
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    widget.didChangeAppLifecycleState(state);
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
        builder: (c, child) => widget.buildMaterialApp(navigatorKey),
        designSize: widget.designSize());
  }
}

class SafePlatform {
  static bool isAndroid() {
    try {
      return p.Platform.isAndroid;
    } catch (e) {
      return false;
    }
  }

  static bool isIOS() {
    try {
      return p.Platform.isIOS;
    } catch (e) {
      return false;
    }
  }

  static bool isWeb() {
    try {
      return kIsWeb;// !p.Platform.isAndroid;
    } catch (e) {
      return false;
    }
  }

  ///判断是否是 鸿蒙Next系统
  static bool isOhos() {
    try {
      return p.Platform.operatingSystem == "ohos";
    } catch (e) {
      return false;
    }
  }
}

class DialogNavigatorObserver extends NavigatorObserver {

  static String? _dialogType;

  @override
  @mustCallSuper
  void didPop(Route route, Route? previousRoute) {
    // logger.info("didpop =============");
    // logger.info(route);
    // logger.info(previousRoute);
    if(route is DialogRoute) _dialogType = null;
  }

  @override
  @mustCallSuper
  void didPush(Route route, Route? previousRoute) {
    // logger.info("didPush =============");
    // logger.info(route);
    // logger.info(previousRoute);
    if(route is DialogRoute) {
      _dialogType = route.settings.name??"other";
    }
  }

  @override
  @mustCallSuper
  void didReplace({Route? newRoute, Route? oldRoute}) {
    // logger.info("didReplace =============");
    // logger.info(newRoute);
    // logger.info(oldRoute);
    if(oldRoute is DialogRoute) _dialogType = null;
  }

  @override
  void didRemove(Route route, Route? previousRoute) {
    // logger.info("didRemove =============");
    // logger.info(route);
    // logger.info(previousRoute);
  }
}

mixin FxState<T extends StatefulWidget> on State<T> {

  void mountedState([VoidCallback? fn]) {
    if(mounted) setState(fn ?? (){});
  }
}

mixin UIOverlayStyleState<T extends StatefulWidget> on State<T> {

  ///[dark] 状态栏是否是黑色
  changeSystemUIOverlayStyle(bool dark) {
    if(dark) {
      SystemChrome.setSystemUIOverlayStyle(FxTheme().darkUiStyleWhiteNavigationBar);
    } else {
      SystemChrome.setSystemUIOverlayStyle(
        const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent, // 状态栏背景透明
          statusBarIconBrightness: Brightness.light, // 图标白色
          statusBarBrightness: Brightness.dark, // iOS 状态栏文字白色
        ),
      );
    }
  }
}

bool _funcThrottle = false;

///函数节流
///
/// [milliseconds] 在设定的时间内不能再次执行函数
void throttle(Function? func,
    {dynamic params, Duration delay = const Duration(milliseconds: 500)}) {
  if (func == null || _funcThrottle) return;
  _funcThrottle = true;
  Timer(delay, () => _funcThrottle = false);
  try {
    if(params == null) {
      func();
    } else {
      func(params);
    }
  } catch (e) {
    rethrow;
  }
}

///函数防抖
///
/// [delay] 函数延迟执行的时长
Function debounce(Function func,
    [Duration delay = const Duration(seconds: 2)]) {
  Timer? timer;
  return () {
    if (timer?.isActive ?? false) {
      timer?.cancel();
    }
    timer = Timer(delay, () {
      func.call();
    });
  };
}